package com.truckdispatching.image;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.graphics.Bitmap;

public class ImageCache {

	private final Object mCacheLock = new Object();

	private HashMap<Integer, SoftReference<Bitmap>> mSoftReferenceCache = new HashMap<Integer, SoftReference<Bitmap>>();

	public Bitmap get(ImageTask task) {
		synchronized (mCacheLock) {
			if (task == null) {
				return null;
			} else {
				return getBitmapFromSoftReferenceCache(task);
			}
		}
	}

	private Bitmap getBitmapFromSoftReferenceCache(ImageTask task) {
		if (mSoftReferenceCache != null) {
			SoftReference<Bitmap> ref = mSoftReferenceCache.get(task.mImageUrl.hashCode());
			if (ref != null) {
				Bitmap bitmap = ref.get();
				if (bitmap != null && !bitmap.isRecycled()) {
					return bitmap;
				}
			}
		}
		return null;
	}

	public Bitmap put(ImageTask task, Bitmap bitmap) {
		if (task == null || bitmap == null || bitmap.isRecycled()) {
			return null;
		}
		synchronized (mCacheLock) {
			return putBitmapIntoSoftReferenceCache(task, bitmap);
		}
	}

	private Bitmap putBitmapIntoSoftReferenceCache(ImageTask task, Bitmap bitmap) {
		if (task != null && task.mImageUrl != null && !task.mImageUrl.equals("") && bitmap != null) {
			Bitmap tempBitmap = getBitmapFromSoftReferenceCache(task);
			if (tempBitmap == null) {
				if (mSoftReferenceCache != null) {
					mSoftReferenceCache.put(task.mImageUrl.hashCode(), new SoftReference<Bitmap>(bitmap));
				}
				return bitmap;
			} else {
				if (bitmap != null && bitmap != tempBitmap) {
					bitmap.recycle();
				}
				return tempBitmap;
			}
		}
		return null;
	}

	public void clear() {
		if (mSoftReferenceCache != null) {
			mSoftReferenceCache.clear();
		}
	}
}
